/**
*  req.ob  主键
*  req.bd  不等于 true/undefined
*  req.bdfield   不等于字段
*  req.dy  大于  true/undefined
*  req.dyfield   大于字段
*  req.xy  小于  true/undefined
*  req.xyfield   小于字段
*  req.in        true/undefined
*  req.infield   多个值字段
*  req.range 范围查询
*  req.rangeField  范围查询字段
*  req.rangeStart  范围开始边界
*  req.rangeEnd    范围结束边界
*  req.as 当前表的别名
*  req.sort 排序 desc/asc 默认desc
*/
module.exports = function (req, select, filedsArr) {
  var pageIndex = req.body.pageIndex || 1,
    pageSize = req.body.pageSize || 10
  var sort = 'DESC'
  // 如果查询参数为-999则删除参数
  for (let key in req.body) {
    if (key === 'pageIndex' || key === 'pageSize' || req.body[key] === '') {
      delete req.body[key]
    }
    if (key === 'sort') {
      sort = req.body[key]
      delete req.body[key]
    }
  }
  var ob = req.ob ? req.ob : 'id'
  var orderTxt = req.as ? ' ORDER BY ' + req.as + '.id ' + sort + ' LIMIT ' : ' ORDER BY ' + ob + ' ' + sort + ' LIMIT '
  var pageSet = orderTxt + (pageIndex - 1) * pageSize + ',' + pageSize;
  // 有参数
  if (Object.getOwnPropertyNames(req.body).length > 0) {
    var arr = [];
    req.wtxt = req.as ? ' WHERE ' + req.as + '.' : ' WHERE '
    for (var key in req.body) {
      if (filedsArr.length && filedsArr.includes(key)) {
        req.body[key] != "" && arr.push(key + " LIKE '%" + req.body[key] + "%'")
      } else {
        if (req.bd && req.bdfield && key == req.bdfield) {
          arr.push(key + "<>" + req.body[key])
        } else if (req.dy && req.dyfield && key == req.dyfield) {
          arr.push(key + ">" + req.body[key])
        } else if (req.range && req.rangeField && key == req.rangeField) {
          arr.push(key + " BETWEEN \"" + req.body[key].split(",")[0] + "\" AND \"" + req.body[key].split(",")[1] + "\"")
        } else if (req.in && req.infield && key == req.infield) {
          arr.push(key + " IN " + "(" + req.body[key] + ")")
        } else {
          req.body[key] !== '' && arr.push(key + "=" + req.body[key])
        }
      }
    }
    var joinMsg = req.as ? " AND " + req.as + '.' : " AND "
    req.sqlTxt = arr.join(joinMsg)
    req.selectSql = req.sqlTxt != "" ? select + req.wtxt + req.sqlTxt + pageSet : select + pageSet
  } else {
    req.selectSql = select + pageSet
    req.sqlTxt = ""
    req.wtxt = ""
  }
}